import pymysql
from typing import List, Tuple

class MariaDBConnector:
    def __init__(self, host: str, port: int, user: str, password: str, db: str):
        self.config = {
            'host': host,
            'port': port,
            'user': user,
            'password': password,
            'db': db,
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor
        }
    
    def _get_connection(self):
        """获取数据库连接"""
        return pymysql.connect(**self.config)

    def execute_query(self, sql: str, params: Tuple = None) -> List[dict]:
        """执行查询语句"""
        try:
            with self._get_connection() as conn:
                with conn.cursor() as cursor:
                    cursor.execute(sql, params or ())
                    return cursor.fetchall()
        except pymysql.Error as e:
            print(f"Database error: {e}")
            return []

    def execute_update(self, sql: str, params: Tuple = None) -> int:
        """执行更新/插入语句"""
        try:
            with self._get_connection() as conn:
                with conn.cursor() as cursor:
                    affected_rows = cursor.execute(sql, params or ())
                    conn.commit()
                    return affected_rows
        except pymysql.Error as e:
            conn.rollback()
            print(f"Database error: {e}")
            return 0

# 使用示例
if __name__ == "__main__":
    # 配置数据库连接信息（替换为实际值）
    db_config = {
        'host': '192.168.32.211',
        'port': 3306,
        'user': 'root',
        'password': 'xj1983SH1216',
        'db': 'support_app_db'
    }
    
    connector = MariaDBConnector(**db_config)
    
    # 示例查询
    results = connector.execute_query("SELECT * FROM users")
    print("Query results:", results)
    
